
import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'dart:ui' as ui;

class FileUtil{

  ///异步获取网络图片并按尺寸缩放
  static Future<ui.Image> getImage(String path,double dWidth,double dHeight) async {
    Completer<ImageInfo> completer = Completer();
    var img = new NetworkImage(path);
    ImageStream imageStream =img.resolve(ImageConfiguration());
    imageStream.addListener(ImageStreamListener((ImageInfo info,bool _){
      completer.complete(info);
    }));
    ImageInfo imageInfo = await completer.future;
    var recorder = ui.PictureRecorder();//使用PictureRecorder对图片进行录制
    Paint paint = Paint();
    Canvas canvas = Canvas(recorder);
    double srcWidth = imageInfo.image.width.toDouble();
    double srcHeight = imageInfo.image.height.toDouble();
    canvas.drawImageRect(imageInfo.image,
        // 使用drawImageRect对图片进行定尺寸填充
        Rect.fromLTWH(0, 0, srcWidth, srcHeight),
        Rect.fromLTWH(0, 0, dWidth.toDouble() ,dHeight.toDouble()), paint);
    ui.Image tempImage;
    tempImage =await recorder.endRecording().toImage(dWidth.toInt(), dHeight.toInt());
    return tempImage;
  }

  ///异步获取网络图片并按尺寸缩放
  static Future<ui.Picture> getPicture(String path,double dWidth,double dHeight) async {
    Completer<ImageInfo> completer = Completer();
    var img = new NetworkImage(path);
    ImageStream imageStream =img.resolve(ImageConfiguration());
    imageStream.addListener(ImageStreamListener((ImageInfo info,bool _){
      completer.complete(info);
    }));
    ImageInfo imageInfo = await completer.future;
    var recorder = ui.PictureRecorder();//使用PictureRecorder对图片进行录制
    Paint paint = Paint();
    Canvas canvas = Canvas(recorder);
    double srcWidth = imageInfo.image.width.toDouble();
    double srcHeight = imageInfo.image.height.toDouble();
    canvas.drawImageRect(imageInfo.image,
        // 使用drawImageRect对图片进行定尺寸填充
        Rect.fromLTWH(0, 0, srcWidth, srcHeight),
        Rect.fromLTWH(0, 0, dWidth.toDouble() ,dHeight.toDouble()), paint);
    ui.Picture tempPicture=recorder.endRecording();
    return tempPicture;
  }


}